#!/usr/bin/env python3
# -*- coding: utf-8 -*-

""" Face Detector """

__author__ = "rency"

import numpy as np
import cv2
import matplotlib.pyplot as plot
import org.rency.face.support.OSSupport as osSupport
import org.rency.face.support.DateSupport as dateSupport
import org.rency.face.config.GlobalVariable as variable
from org.rency.face.domain.DetectResult import DetectResult


class FaceDetector:

    def __init__(self):
        self.config = variable.CONFIGURATION
        self.faceCascade = self.config.get(variable.CONF_OPENCV_SECTION, variable.CONF_OPENCV_FACE_CASCADE)
        self.eyeCascade = self.config.get(variable.CONF_OPENCV_SECTION, variable.CONF_OPENCV_EYE_CASCADE)
        self.home = osSupport.OSSupport.getHome()
        self.faceDir = self.home+variable.APPLICATION_NAME_IDENTITY + osSupport.OSSupport.getSeparator()+'faces'+osSupport.OSSupport.getSeparator()
        isExists = osSupport.OSSupport.exists(self.faceDir)
        if not isExists:
            osSupport.OSSupport.mkdir(self.faceDir)

    def gface(self, image):
        # 创建classifier
        faceCascade = cv2.CascadeClassifier(self.faceCascade)
        eyeCascade = cv2.CascadeClassifier(self.eyeCascade)
        # 设定灰度
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        # 识别面部
        faces = faceCascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE)

        faceCount = len(faces)
        print("Found {0} faces!".format(faceCount))

        detectResult = DetectResult()
        if faceCount > 0:
            detectResult.setSuccess(True)
            detectResult.setOrgiFace(image.copy())
            # 画方框
            for (x, y, w, h) in faces:
                img = cv2.rectangle(image, (x, y), (x + w, y + h), (255, 0, 0), 2)
                roi_gray = gray[y:y + h, x:x + w]
                roi_color = img[y:y + h, x:x + w]
                eyes = eyeCascade.detectMultiScale(roi_gray)
                for (ex, ey, ew, eh) in eyes:
                    cv2.rectangle(roi_color, (ex, ey), (ex + ew, ey + eh), (0, 255, 0), 2)
                detectResult.setColorFace(img)
        return detectResult

    def detect(self):
        cap = cv2.VideoCapture(0)
        while self.cap.isOpened():
            # 读取帧摄像头
            success, image = self.cap.read()
            if success is True:
                # 输出当前帧
                detectResult = self.gface(image)
                if detectResult.isSuccess is True:
                    imgName = self.faceDir + dateSupport.DateSupport.getDateNowStr() + '.jpg'
                    print('save face image to {0}'.format(imgName))
                    self.cv.imwrite(imgName, detectResult.orgiFace)
                    self.cv.imshow("Camera", detectResult.colorFace)
                else:
                    self.cv.imshow("Camera", image)

                if self.cv.waitKey(0) & 0xFF == ord('q'):
                    break
            else:
                print("undetect camera!!!")
                break

    def __del__(self):
        """
        释放资源
        :return:
        """
        # self.cap.release()
        cv2.destroyAllWindows()


if __name__ == '__main__':
    faceDetector = FaceDetector()
    image = cv2.imread('D:/opt/1002.jpg')
    cv2.imshow("Camera", image)
    detectResult = faceDetector.gface(image)
    while True:
        if cv2.waitKey(0) & 0xFF == ord('q'):
            break
